/*
 * @Author: whr2349
 * @Date: 2021-07-08 15:04:52
 * @LastEditors: whr2349
 * @LastEditTime: 2021-07-08 16:16:15
 * @Description: file content
 * @FilePath: \back\app\extend\helper.js
 */
module.exports = {

    /**
     * @description: 根据条件（顶层条件）递归查询某个模型输出嵌套结构
     * @Date: 2021-07-08 15:41:33
     * @param { Object } param 
     *  * model: "Organization",//要递归的model对象
     *  * pNname: "",//根节点字段名，相当于父级节点名 默认pid   
     *  * pValue: "",//根节点字段值
     *  * name: "",//节点名 默认_id
     * @return { model } result:mongoose
     */
    async deepTree(param) {

        param.pName = param.pName ?? 'pid'
        param.pValue = param.pValue ?? ''
        param.name = param.name ?? '_id'

        const { model, pName, pValue, name } = param

        const { ctx } = this

        let root = await ctx.model[model].find({ [pName]: pValue })

        async function getChildren(data) {
            let arr = []
            data.forEach(async (item) => {
                // item._doc.children = await ctx.model.Organization.find({ superiorKey: item.key })
                arr.push(ctx.model.Organization.find({ [pName]: item[name] }))
            })
            const child = await Promise.all(arr)

            for (let [index, item] of child.entries()) {
                data[index]._doc.children = item
                if (item.length > 0) {
                    item = await getChildren(item)
                }
            }
            return data
        }

        const result = await getChildren(root)

        return result
    },
}